import { Order, OrderDocument } from '@app/database/schemas/order.schema';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';

@Injectable()
export class OrdersService {
  constructor(
    @InjectModel('Order')
    private readonly orderModel: Model<OrderDocument>,
  ) {}

  create(order: Order) {
    return this.orderModel.create(order);
  }

  async findAll(query: any) {
    let { size, currentPage, status = null } = query || {};
    let where: any = { status: { $ne: 0 } };
    if (status) {
      where.status.$eq = status;
    }
    size = Number(size);
    currentPage = Number(currentPage);
    const res = await this.orderModel
      .find(where)
      .populate('user')
      .skip((currentPage - 1) * size)
      .limit(size)
      .sort({ _id: -1 });
    const total = await this.orderModel.countDocuments(where);
    return {
      items: res,
      total,
    };
  }

  async findOne(id: string) {
    const res = await this.orderModel
      .findOne({ _id: id })
      .populate('user')
      .populate('cars');
    return res;
  }

  update(id: string, order: Order) {
    return this.orderModel.updateOne({ _id: id }, order);
  }

  remove(id: string) {
    return this.orderModel.deleteOne({ _id: id });
  }

  option() {
    return {
      title: '订单列表',
      descriptions: '显示和处理订单列表',
      items: [
        {
          label: '订单ID',
          prop: '_id',
          type: 'input',
          noSelect: true,
        },
        {
          label: '用户名',
          prop: 'user',
          sub: 'username',
          type: 'input',
          noSelect: true,
        },
        {
          label: '地址',
          prop: 'user',
          sub: 'address',
          type: 'input',
          noSelect: true,
        },
        {
          label: '订单状态',
          prop: 'status',
          type: 'select',
          keyName: 'name',
          items: [
            {
              name: '待发货',
              _id: 1,
            },
            {
              name: '已发货',
              _id: 2,
            },
          ],
        },
        {
          label: '快递单号',
          prop: 'express',
          type: 'input',
          display: true,
        },
      ],
    };
  }
}
